const {src, dest, series, watch} = require('gulp');
const plugins = require("gulp-load-plugins")();
const del = require('del');
const browserSync = require('browser-sync').create();

const reload = browserSync.reload;

// 压缩 js uglifyjs
function js(callback){
    src('src/js/*.js')
        .pipe(plugins.uglify())
        .pipe(dest('./dist/js'))
        .pipe(reload({ stream: true}));
    callback()
}

// 对 scss/less 编译、压缩, 输出css文件
function css(callback) {
    src('src/css/*.scss')
        .pipe(plugins.sass({ outputStyle: 'compressed'}))
        .pipe(plugins.autoprefixer({
            cascade: false,
            remove: false
        }))
        .pipe(reload({ stream: true}))
        .pipe(dest('./dist/css'));
    callback()
}

// 监听这些文件的变化
function watcher() {
    watch('src/js/*.js', js);
    watch('src/css/*.scss', css);
}

// 删除dist目录中的内容
function clean(callback) {
    del('./dist');
    callback()
}

function serve(callback){
    browserSync.init({
        server: {
            baseDir: './'
        }
    });
    callback();
}

exports.scripts = js;
exports.styles = css;
exports.clean = clean;
exports.default = series([
    clean,
    js,
    css,
    serve,
    watcher
])